<template>
    <el-dialog v-model="visible" :title="title" :width="width" @close="resetForm" @open="init" :close-on-press-escape="false">
        <el-form label-width="110px" label-position="left" label-suffix="：" :model="position" :rules="rules" ref="formRef">
            <el-form-item label="编码" prop="id" style="display: none"/>
          <el-form-item label="上级部门" prop="deptId">
            <el-select v-model="position.deptId" class="m-2" placeholder="选择部门">
              <template v-for="(item) in deptOptions">
                <el-option :label="item.label" :value="item.value"/>
              </template>
            </el-select>
          </el-form-item>
            <el-form-item label="上级岗位" prop="parentId">
                <el-select v-model="position.parentId" placeholder="选择上级岗位">
                    <template v-for="(item) in this.$store.state.positionOptions">
                        <el-option :label="item.label" :value="item.value" :disabled="item.enabled===0" v-if="item.value!==position.id"/>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="岗位名称" prop="name">
                <el-input v-model="position.name" placeholder="请输入岗位名称"/>
            </el-form-item>
            <el-form-item label="岗位编码" prop="code">
                <el-input v-model="position.code" placeholder="请输入岗位编码"/>
            </el-form-item>
            <el-form-item label="是否启用" prop="enabled">
                <el-radio-group v-model="position.enabled">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">停用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input-number v-model="position.sort" :min="1"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="position.remark"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="default" @click="visible=false">取消</el-button>
            <template v-if="type===0">
                <el-button type="primary" @click="submitAdd">确认</el-button>
            </template>
            <template v-else>
                <el-button type="primary" @click="submitUpdate">确认</el-button>
            </template>
        </template>
    </el-dialog>
</template>

<script>
    import {ElMessage} from "element-plus";
    import {
        addPosition,
        getPositionOptions, hasSomeCodePosition,
        hasSomeNamePosition,
        updatePosition
    } from "../../../../network/sys/position";
    import {getDeptOptions} from "../../../../network/sys/dept";
    import {getCurrentInstance, reactive, ref, toRefs} from "vue";

    export default {
        name: "PositionForm",
        emits:['refresh-data'],
        props:{width: ''},
        setup(props,{emit}){
            const globalProperties = getCurrentInstance()?.appContext.config.globalProperties;
            const visible = ref(false);//是否展示
            const formRef = ref(null);

            const validateName = (rule,value,callback)=>{
                hasSomeNamePosition({
                    id: form.position.id,
                    name: value
                }).then(vo=>{
                    if(vo){
                        callback(new Error('已存在相同名称的岗位'));
                    }
                    callback();
                })
            }

            const validateCode = (rule,value,callback)=>{
                hasSomeCodePosition({
                    id: form.position.id,
                    code: value
                }).then(vo=>{
                    if(vo){
                        callback(new Error('已存在相同编码的岗位'));
                    }
                    callback();
                })
            }

            const form = reactive({
                position: {
                    id: null,
                    deptId: null,
                    parentId: null,
                    name: null,
                    enabled: 1,
                    remark: null,
                    sort: 1,
                    code: null
                },
                rules: {
                    name: [
                        {required: true, message: '请输入岗位名称',trigger: 'blur'},
                        {validator: validateName, trigger: 'blur'}
                    ],
                    code: [
                        {required:true, message: '请输入岗位编码',trigger: 'blur'},
                        {validator: validateCode, trigger: 'blur'}
                    ]
                },
                setPosition: ({ id, parentId, name, enabled, remark, sort, code})=>{
                    form.position.id = id;
                    form.position.parentId = parentId;
                    form.position.name = name;
                    form.position.enabled = enabled?enabled:1;
                    form.position.remark = remark;
                    form.position.sort = sort?sort:1;
                    form.position.code = code;
                },
                resetForm(){
                    formRef.value.resetFields();
                    formRef.value.clearValidate();
                    // console.log('formRef.value.resetFields() after',form.position)
                },
                submitAdd(){
                    formRef.value.validate((valid)=>{
                        if(valid){
                            addPosition(form.position).then(vo=>{
                                globalProperties.$response.handle({
                                    data: vo,
                                    success: '添加成功',
                                    error: '添加失败',
                                    successFn: ()=>{
                                        emit('refresh-data')//刷新数据表格
                                        visible.value = false;
                                    }
                                })
                            })
                        }else{
                            ElMessage.error('请先完善表单!')
                        }
                    })
                },
                submitUpdate(){
                    formRef.value.validate((valid)=>{
                        if(valid){
                            updatePosition(form.position).then(vo=>{
                                globalProperties.$response.handle({
                                    data: vo,
                                    success: '修改成功',
                                    successFn: ()=>{
                                        emit('refresh-data');
                                        visible.value = false;
                                    },
                                    error: '删除失败',
                                    log: '删除结果'
                                })
                            })
                        }else{
                            ElMessage.error('请先完善表单!');
                        }
                    })
                }
            })
            return {
                visible,
                formRef,
                ...toRefs(form)
            }
        },
        data(){
            return{
                type: 0,//0为添加表单，1为修改表单
                title: '',//表单名称
                deptOptions:[]
            }
        },
        methods:{
            loadPositionOptions(){
                getPositionOptions().then(vo=>{
                    this.$response.handle({
                        data:vo,
                        successFn: ()=>{
                            this.$store.commit('setPositionOptions',vo.data);
                        },
                        error: '获取岗位选项失败',
                        log: '岗位选项信息'
                    })
                })
            },
            init(){
                if(this.$store.state.positionOptions.length===0){
                    this.loadPositionOptions();
                }
            }
        },
      mounted() {
        getDeptOptions().then((das)=>{
          this.deptOptions = das.data
        })
      },
      created() {
            this.init();
        }
    }
</script>

<style scoped>
    .el-select-dropdown__item{
        width: 100%;
    }
    /*.el-cascader-node{*/
    /*    width: 100%;*/
    /*}*/
    .explain{
        font-size: 12px;
        color: #a1a1a1;
    }
    .el-select-dropdown{
        width: 210px;
    }
    .el-select-dropdown__wrap{
        width: 210px;
    }
    .el-select{
        width: 220px;
    }
</style>
<style>
.el-select-dropdown{
    width: 220px;
}
</style>
